import { forwardRef, useImperativeHandle, useReducer } from 'react'
import { Root } from './context'
import reducer from './reducer'
//表单组件
const Form = forwardRef((props, ref) => {
  const [state, dispatch] = useReducer(reducer, {})
  const { children, style = {} } = props;
  useImperativeHandle(ref, () => ({
    //登录函数
    async onSignIn (url) {
      return fetch(url, {
        method: "post",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(state)
      }).then(res => res.json()).then(data => data)
    },
    //注册函数
    async onSignUp (url) {
      return fetch(url, {
        method: "post",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(state)
      }).then(res => res.json()).then(data => data)
    },
  }))
  return (
    <div style={{ ...style }}>
      <Root value={{
        state,
        dispatch
      }}>
        {children}
      </Root>
    </div>
  )
});
export default Form;